﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Communication.Packets;
using Utilities.IO;
using Utilities.Conversion;

namespace ConnectServer.Protocol
{
    /// <summary>
    /// ConnectServer Packet type.
    /// </summary>
    public abstract class ConnectServerPacket : Packet
    {
        public new static int ID = 0xF4;

        #region Ctor
        /// <summary>
        /// Ctor
        /// </summary>
        /// <param name="type">The type of the packet</param>
        /// <param name="sub_id">The sub-id of the packet</param>
        public ConnectServerPacket(PacketType type, int sub_id)
            : base(type, ID)
        {
            this.m_subId = sub_id;
        }
        #endregion

        #region Serialization & Deserialization
        public ConnectServerPacket(BufferedStream buffer)
            : base(buffer)
        {
            // check if this is the right packet type.
            if (this.m_id != ID)
            {
                throw new InvalidPacketIDError();
            }
            EndianBinaryReader reader = new EndianBinaryReader(EndianBitConverter.Big, buffer);
            this.m_subId = reader.ReadByte();
        }

        public override void Serialize(BufferedStream buffer)
        {
            // TODO: change to an elegant way.
            byte[] temp_buffer = new byte[buffer.Length];
            buffer.Seek(0, SeekOrigin.Begin);
            buffer.Read(temp_buffer, 0, temp_buffer.Length);
            buffer.Seek(0, SeekOrigin.Begin);

            EndianBinaryWriter writer = new EndianBinaryWriter(EndianBitConverter.Big, buffer);
            writer.Write((byte)this.m_subId);
            writer.Flush();

            writer.Write(temp_buffer, 0, temp_buffer.Length);

            base.Serialize(buffer);
        }
        #endregion

        #region Fields
        protected int m_subId;
        #endregion
    }
}
